<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>商品管理</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" type="text/css" href="lib/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-switch.css">
    <link rel="stylesheet" type="text/css" href="css/pager.css">

    <script src="lib/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="lib/bootstrap-switch.js"></script>
    <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script src="../static/js/bootstrap-paginator.js"></script>
    <script src="js/pager.js"></script>
    <!--    <script src="js/utils.js"></script>-->
    <style type="text/css">
        .col0{
            width: 5px;
        }
        .col1{
            width: 10px;
        }
        .col2{
            width: 50px;
        }
        .col3{
            width: 150px;
        }
        .col4{
            width: 8px;
        }
        .col5{
            width: 10px;
        }
        .col6{
            width: 30px;
        }
        .col6{
            width: 50px;
        }
        .col7{
            width: 50px;
        }
        .col8{
            width: 10px;
        }
    </style>

    <script>

        //分页条
        function pager(total,size,keyword){
            var paras = {
                keyword:keyword,
                limit:size,
                limits:[5,10,15],
                groups:3,
                count:total
            }
            $("#pager2").YlpPage(paras);
        }

        function get_users_keyword(keyword,currentPage, pageSize){
            let datas;
            $.ajax({
                url:"/product/keyword",
                method:"GET",
                data:{
                    keyword,
                    currentPage:currentPage,
                    pageSize: pageSize

                },
                success:(data,status)=>{
                    datas = data;
                    render_data(data.records);
                    console.log(data.records);

                },
                error:()=>{
                    console.log("查询失败!");
                }
            })

        }





        //发送请求 请求商品数据

        function get_users(currentPage, pageSize){
            let datas;
            $.ajax({
                url:"/product/all",
                method:"GET",
                async:false,
                data:{
                    currentPage,
                    pageSize
                },
                success:(data,status)=>{

                    datas = data;
                },
                error:()=>{
                    console.log("商品数据请求失败!")
                }
            })
            return datas;
        }

        // 格式化时间字符串
        function formatDateTime(dateTimeString) {
            const date = new Date(dateTimeString);
            const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
            const formattedTime = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
            return `${formattedDate} ${formattedTime}`;
        }



        //渲染用户数据到表格
        function render_data(products){
            //清除原本数据
            $("#product_list").empty();
            let products1 = Array.from(products)
            //遍历用户数据将数据渲染到页面中
            //遍历商品数据将数据渲染到页面中
            let i = 1;
            products1.map((product) =>{

                let id=product.id;
                let img=product.imgpath;
                let name = product.name;
                let price = product.price;
                let status = product.status;
                let detail = product.detail;
                if (status === 1){
                    status="在售"
                }else if (status ===2){
                    status="下架"
                }else if (status === 3){
                    status="删除"
                }
                let cid = product.cid;
                if(cid === 1){
                    cid="绿茶"
                }else if (cid ===2){
                    cid="乌龙茶"
                }else if (cid === 3){
                    cid="白茶"
                }else if (cid ===4){
                    cid="红茶"
                }else if (cid === 5){
                    cid="普洱茶"
                }

                let time = product.craeteTime;
                time=formatDateTime(time);
                $("#product_list").append("<tr><td>"+i+++"</td><td>"+id+"</td><td>"+name+"</td><td>"+detail+"</td><td>"+cid+"</td><td>￥"+price+"</td><td>"+status+"</td><td>"+time+`</td><td><button onclick='edit1(this)'  id=\"updateBtn\" type=\"button\" class=\"btn btn-info\" data-toggle=\"modal\"data-target=\"#updDialog\" >修改</button><button id=\"delete-btn\" type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" onclick='edit2(this)'data-target=\"#deleteDialog\">删除</button>`)


            })
        }
        function edit1(val){
            //这里就是val，别以为写错了，如果写成this会报错：Uncaught SyntaxError: Unexpected token 'this'，这是转过来的参数值的意思
            let value = $(val).parent().parent().find("td");
            $("#upd_pid").val(value.eq(1).text())
            $("#upd_pname").val(value.eq(2).text())
            // $("#upd_categroy").val(value.eq(4).text())
            // $("#upd_status").val(value.eq(6).text())
            $("#upd_pdetail").val(value.eq(3).text())
            $("#upd_pprice").val(value.eq(5).text())

            if (value.eq(6).text()=="在售")
                $("select[name='ups']").val(1);
            else if (value.eq(6).text()=="下架")
                $("select[name='ups']").val(2);
            else if (value.eq(6).text()=="删除")
                $("select[name='ups']").val(3);

            if(value.eq(4).text()=="绿茶")
                $("select[name='s']").val(1);
            else if (value.eq(4).text()=="乌龙茶")
                $("select[name='s']").val(2);
            else if (value.eq(4).text()=="白茶")
                $("select[name='s']").val(3);
            else if (value.eq(4).text()=="红茶")
                $("select[name='s']").val(4);
            else if (value.eq(4).text()=="普洱茶")
                $("select[name='s']").val(5);
        }

        function edit2(val){


            //这里就是val，别以为写错了，如果写成this会报错：Uncaught SyntaxError: Unexpected token 'this'，这是转过来的参数值的意思
            let value = $(val).parent().parent().find("td");
            $("#delete_pid").val(value.eq(1).text())
            $("#delete_pname").val(value.eq(2).text())
        }

        $(function (){

            //初始化分页条
            let  data = get_users(1,5);
            //渲染用户数据到页面
            render_data(data.records);
            //获取数据的总数
            let total = data.total;
            let size= data.size;
            //初始化分页栏
            pager(total,size);


            // 给 文件选择框 添加 change 事件
            let file
            $("#uploadImg").change((e) => {
                file = e.target.files[0];
                console.log(file);
            })


            //给筛选按钮绑定事件
            $("#queryBtn").click(() =>{

                let keyword = $("#content").val();
                let status = $("#select").val();
                console.log(keyword);
                if (keyword){
                    $.ajax({
                        url:"/product/keyword",
                        method:"GET",
                        data:{
                            keyword,
                            currentPage:1,
                            pageSize: 5

                        },
                        success:(data,status)=>{
                            document.getElementById("pager2_YlpPage").remove();
                            render_data(data.records);
                            // console.log(data.records);
                            //获取数据的总数
                            let total = data.total;
                            let size= data.size;

                            //初始化分页栏
                            pager(total,size,keyword);
                        },
                        error:()=>{
                            console.log("查询失败!");
                        }
                    })
                }else{
                    console.log('all')
                    $.ajax({
                        url:"/product/all",
                        method:"GET",
                        data:{
                            currentPage: 1,
                            pageSize: 5
                        },
                        success:(data,status)=>{
                            document.getElementById("pager2_YlpPage").remove();
                            render_data(data.records);
                            //获取数据的总数
                            let total = data.total;
                            let size= data.size;

                            //初始化分页栏
                            pager(total,size);
                            // console.log(data.records);
                        },
                        error:()=>{
                            console.log("查询失败!");
                        }
                    })

                }
                if(status){
                    $.ajax({
                        url:"/product/select/status",
                        method:"GET",
                        data:{
                            status
                        },
                        success:(data,status)=>{

                            render_data(data.records);
                            // console.log(data.records);

                        },
                        error:()=>{
                            console.log("查询失败!");
                        }
                    })
                }

            })

            //给添加按钮绑定事件
            $("#addBtn").click(() => {
                let name = $("#name").val();
                let cid = $("#cid").val();
                let status = $("#p_status").val();
                let detail = $("#detail").val();
                // let imgpath = $("#imgpath").val();
                let img = file;
                let  price = $("#price").val();

                // 验证数据完整性
                if (!(name && cid && price)) {
                    $("#msg").text("商品名称、商品分类、商品价格为必填项！").css("color", "red").show();
                    return;
                }

                $("#msg").hide();

                console.log("name=", name)
                console.log("cid=", cid)
                console.log("detail=", detail)
                console.log("price=", price)
                console.log("img=", img)

                // 将数据都封装到 FormData

                let formData = new FormData();
                formData.append("cid", cid);
                formData.set("cid",cid);
                console.log(formData.get("cid"))
                formData.append("name", name);
                formData.append("status",status);
                formData.append("detail", detail);
                formData.append("price", price);
                formData.append("img", img);


                $.ajax({
                    url: "/product/add",
                    type: "POST",
                    processData: false,
                    contentType: false,
                    data: formData,

                    success: (data) => {
                        if (data.isOk) {
                            $("#msg").text("商品添加成功！").css("color", "yellowgreen").show();

                        }
                        $("#msg").text(data.msg).css("color", "yellowgreen").show();
                        //初始化分页条
                        let  data1 = get_users(1,5);
                        //渲染用户数据到页面
                        render_data(data1.records);

                    },
                    error: () => {
                        $("#msg").text("添加商品请求发送失败！").css("color", "red").show();
                    },

                });

            })

            //给修改按钮绑定事件
            $("#upd_addBtn").click(()=>{

                let id = $("#upd_pid").val();
                let name = $("#upd_pname").val();
                let cid = $("select[name='s']").val();
                let status =  $("select[name='ups']").val();
                let detail = $("#upd_pdetail").val();
                let  price = $("#upd_pprice").val().substr(1)


                console.log(id);
                console.log(name);
                console.log(cid);
                console.log(status);
                console.log(detail);
                console.log(price);


                $.ajax({
                    url: `/product/update?id=${id}&&status=${status}&&cid=${cid}&&price=${price}&&detail=${detail}&&name=${name}`,
                    // url:"/product/update",
                    type: "POST",
                    processData: false,
                    contentType: false,

                    success: (data) => {
                        console.log(data);
                        if (data.isOk) {
                            $("#msg2").text("商品修改成功！").css("color", "yellowgreen").show();
                        }
                        $("#msg2").text(data.msg).css("color", "yellowgreen").show();
                    },
                    error: () => {
                        $("#msg2").text("修改商品请求发送失败！").css("color", "red").show();
                    }
                });
            })

            //给删除商品确定按钮绑定事件
            $("#delete_Btn").click(()=>{
                let id = $("#delete_pid").val();
                let username = $("#delete_pname").val();
                console.log(username);
                $.ajax({
                    url:"/product/delete",
                    method:"GET",
                    data:{
                        id
                    },
                    success:(data,status)=>{

                        console.log(data);
                        if (data.isOk) {
                            $("#msg3").text("商品修改成功！").css("color", "yellowgreen").show();
                        }
                        $("#msg3").text(data.msg).css("color", "yellowgreen").show();

                    },
                    error:()=>{
                        console.log("删除失败!");
                    }
                })

            })



        })

    </script>


</head>
<body>
<!--the top nav begin-->
<div class="navbar navbar-default" role="navigation">
    <div class="navbar-inner">
        <div class="navbar-header">
            <a class="navbar-brand" href="index.html">茶韵商城后台系统</a>
        </div>
        <ul class="nav navbar-nav pull-right">
            <li id="fat-menu" class="dropdown">
                <a href="#" role="button" class="dropdown-toggle" data-toggle="dropdown">
                    <span class="glyphicon glyphicon-user"></span> 用户名
                    <span class="glyphicon glyphicon-chevron-down"></span>
                </a>
                <ul class="dropdown-menu" role="menu">
                    <li role="presentation"><a role="menuitem" tabindex="-1" href="updateadmin.html">我的账户</a></li>
                    <li role="presentation"><a role="menuitem" tabindex="-1" href="login.html">登出</a></li>
                </ul>
            </li>
        </ul>
    </div>
</div>
<!--the top nav end-->
<!--the sidebar nav begin -->
<div class="sidebar-nav">
    <a href="index.html" class="nav-header" ><span class="glyphicon glyphicon-home"></span> 管理中心 首页</a>

    <a href="category.html" class="nav-header"><span class="glyphicon glyphicon-hd-video"></span> 分类管理</a>

    <a href="product.html" class="nav-header"><span class="glyphicon glyphicon-eye-open"></span> 商品管理 </a>

    <a href="order.html" class="nav-header"><span class="glyphicon glyphicon-eye-open"></span> 订单管理 </a>

    <a href="userlist.html" class="nav-header"><span class="glyphicon glyphicon-eye-open"></span> 账户管理</a>

    <a id="outLink" href="login.html" class="nav-header" ><span class="glyphicon glyphicon-log-out"></span> 登出</a>
</div>
<!--the siderbar nav en-->

<div class="content">
    <div class="header">
        <!--page title begin-->

        <!--提示框-->
        <div id="ok" class="alert alert-success" style="position: fixed; z-index: 99; width: 80%; display: none;">
            操作成功！
        </div>

    </div>

    <div class="container">

        <!--the toolbar begin -->
        <div class="toolbar">
            <div class="row">
                <div class="col-xs-6">
                    <form class="form-inline pull-right" id="device-search" role="form">
                        <div class="form-group">选择商品状态:</div>
                        <div class="form-group">
                            <select class="form-control" id="select">
                                <option value="">所有商品</option>
                                <option value="1">在售</option>
                                <option value="2">下架</option>
                                <option value="3">删除</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <input id="content" type="text" class="form-control" placeholder="商品名称……">
                        </div>
                        <button id="queryBtn" type="button" class="btn btn-default">筛选</button>
                        <button id="btn-add-product" type="button" class="btn btn-success" data-toggle="modal" data-target="#addDialog">新增商品
                        </button>
                    </form>
                </div>
            </div>

        </div>


        <!--all user detail begin -->
        <div class="panel panel-default" id="all-device-detail">
            <div class="panel-heading">
                <h5>所有商品信息</h5>

            </div>
            <table class="table">
                <thead>
                <tr>
                    <th class="col0">序号</th>
                    <th class="col1">商品编号</th>
                    <th class="col2">商品名称</th>
                    <th class="col3">商品详情</th>
                    <th class="col8"> 商品分类</th>
                    <th class="col4">价格</th>
                    <th class="col5">状态</th>
                    <th class="col6">创建时间</th>
                    <th class="col7">操作</th>
                </tr>
                </thead>
                <tbody id="product_list"></tbody>
                <tr>
                </tr>
            </table>
        </div>

        <!--分页控件-->
        <div style="margin: 40px 0;text-align: center">
            <div id="pager2"> </div>
        </div>
    </div>
    <!--the container end -->


    <!-- 添加对话框 -->
    <div class="modal fade" id="addDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">创建商品</h4>
                </div>
                <div class="modal-body row">
                    <form action="#" class="form-horizontal" id="add-user" role="form" enctype="multipart/form-data"
                          id="uploadForm" method="post">
                        <div class="form-group">
                            <label for="name" class="col-xs-4 control-label">商品名称<span style="color: red">*</span></label>
                            <div class="col-xs-6">
                                <input type="text" class="form-control" id="name">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="cid" class="col-xs-4 control-label">商品分类<span style="color: red">*</span></label>
                            <div class="col-xs-6">
                                <select id="cid" class="form-control">
                                    <option value="">选择商品类别</option>
                                    <option value="1">绿茶</option>
                                    <option value="2">乌龙茶</option>
                                    <option value="3">白茶</option>
                                    <option value="4">红茶</option>
                                    <option value="5">普洱茶</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="p_status" class="col-xs-4 control-label">商品状态<span style="color: red">*</span></label>
                            <div class="col-xs-6">
                                <select id="p_status" class="form-control">
                                    <option value="">选择商品状态</option>
                                    <option value="1">在售</option>
                                    <option value="2">下架</option>
                                    <option value="3">删除</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="detail" class="col-xs-4 control-label">商品描述</label>
                            <div class="col-xs-6">
                                <textarea class="form-control" id="detail" name="device-description" rows="4"
                                          maxlength="150"></textarea>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="uploadImg" class="col-xs-4 control-label">商品图片</label>
                            <div class="col-xs-6">
                                <input type="file" id="uploadImg" name="uploadImg">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="price" class="col-xs-4 control-label">商品价格<span style="color: red">*</span></label>
                            <div class="col-xs-6">
                                <input type="text" class="form-control" id="price">
                            </div>
                        </div>
                        <div id="msg" style="text-align: center;color: red"></div>

                    </form>
                    <div id="msg1" style="text-align: center;color:red;display: none;">请将数据填写完整！</div>
                </div>
                <div class="modal-footer">
                    <button id="closeBtn" type="button" class="btn btn-default" data-dismiss="modal" onclick="location.reload()">关闭</button>
                    <button id="addBtn" type="button" class="btn btn-primary">添加</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->


    <!-- 修改 -->
    <div class="modal fade" id="updDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel1">修改分类</h4>
                </div>
                <div class="modal-body row">
                    <form action="#" class="form-horizontal" id="add-user1" role="form" enctype="multipart/form-data"
                          id="uploadForm2" method="post">
                        <div class="form-group">
                            <label for="upd_pid" class="col-xs-4 control-label">商品编号</label>
                            <div class="col-xs-6">
                                <input  id="upd_pid"type="text" class="form-control" disabled = "disabled"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="upd_pname" class="col-xs-4 control-label">商品名称</label>
                            <div class="col-xs-6">
                                <input type="text" class="form-control" id="upd_pname">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="upd_categroy" class="col-xs-4 control-label">商品分类</label>
                            <div class="col-xs-6">
                                <select id="upd_categroy" class="form-control" name="s">
                                    <option value="1">绿茶</option>
                                    <option value="2">乌龙茶</option>
                                    <option value="3">白茶</option>
                                    <option value="4">红茶</option>
                                    <option value="5">普洱茶</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="upd_pdetail" class="col-xs-4 control-label">商品描述</label>
                            <div class="col-xs-6">
                                <textarea class="form-control" id="upd_pdetail" name="device-description" rows="4"
                                          maxlength="150"></textarea>
                            </div>
                        </div>


                        <div class="form-group">
                            <label for="upd_pprice" class="col-xs-4 control-label">商品价格</label>
                            <div class="col-xs-6">
                                <input type="text" class="form-control" id="upd_pprice">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="upd_status" class="col-xs-4 control-label">商品状态</label>
                            <div class="col-xs-6">
                                <select id="upd_status" class="form-control" name="ups">
                                    <option value="1">在售</option>
                                    <option value="2">下架</option>
                                    <option value="3">删除</option>
                                </select>
                            </div>
                        </div>
                        <div id="msg2" style="text-align: center;color: red"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button id="upd_closeBtn" type="button" class="btn btn-default" data-dismiss="modal" onclick="location.reload()">关闭</button>
                    <button id="upd_addBtn" type="button" class="btn btn-primary">确定</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

    <!--删除-->
    <div class="modal fade" id="deleteDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel2">确定删除商品信息</h4>
                </div>
                <div class="modal-body row">
                    <form action="#" class="form-horizontal" id="delete-proudct" role="form" enctype="multipart/form-data"
                          id="uploadForm3" method="post">
                        <div class="form-group">
                            <label for="delete_pid" class="col-xs-4 control-label">商品编号</label>
                            <div class="col-xs-6">
                                <input  id="delete_pid"type="text" class="form-control" disabled = "disabled"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="delete_pname" class="col-xs-4 control-label">商品名称</label>
                            <div class="col-xs-6">
                                <input type="text" class="form-control" id="delete_pname" disabled = "disabled">
                            </div>
                        </div>

                        <div id="msg3" style="text-align: center;color: red"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button id="delete_closeBtn" type="button" class="btn btn-default" data-dismiss="modal" onclick="location.reload()">关闭</button>
                    <button id="delete_Btn" type="button" class="btn btn-primary">确定</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->



</div>
<!--the content end -->
<script src="lib/bootstrap/js/bootstrap.js"></script>

<!--全选按钮实现-->
<script>


    $(function () {
        $("#all").click(function () {
            var checked_status = this.checked;
            $("input[name=device-permission]").each(function () {
                this.checked = checked_status;
            });
        });
    });
</script>
</body>
</html>
